/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gatewinapp;

import gate.Corpus;
import gate.DataStore;
import gate.Factory;
import gate.FeatureMap;
import gate.Gate;
import gate.ProcessingResource;
import gate.creole.ANNIEConstants;
import gate.creole.SerialAnalyserController;
import gate.creole.ir.DefaultIndexDefinition;
import gate.creole.ir.DocumentContentReader;
import gate.creole.ir.IndexField;
import gate.creole.ir.IndexedCorpus;
import gate.creole.ir.Search;
import gate.creole.ir.lucene.LuceneSearch;
import gate.util.Err;
import gate.util.GateException;
import gate.util.Out;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author Viet
 */
public class MainFrame extends javax.swing.JFrame {

    private static InformationRetrievalApp irApp;
    private static DataStore sds;
    private static Search search;
    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
        
        // cấu hình txtResult
        txtResult.setContentType("text/html");
        txtResult.setEditorKit(JTextPane.createEditorKitForContentType("text/html"));
        txtResult.addHyperlinkListener(new MyHyperlinkListener());
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTextField2 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btnSearch = new javax.swing.JButton();
        txtQuery = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtResult = new javax.swing.JTextPane();
        btnAdvance = new javax.swing.JButton();

        jTextField2.setText("jTextField2");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("GATE Search Engine - Nhóm 7");

        jLabel1.setText("GATE");

        btnSearch.setText("Tìm Kiếm");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        txtQuery.setToolTipText("enter search query");

        txtResult.setEditable(false);
        jScrollPane1.setViewportView(txtResult);

        btnAdvance.setText("Nâng Cao");
        btnAdvance.setActionCommand("btnAdvance");
        btnAdvance.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdvanceActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnAdvance)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtQuery, javax.swing.GroupLayout.PREFERRED_SIZE, 377, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnSearch)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSearch)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtQuery, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAdvance)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        String strQuery = txtQuery.getText();
        Query q = new Query(strQuery);
        try {
            searchAndDisplayResult(q);
        }
        catch(Exception ex) {
            ex.printStackTrace(Err.getPrintWriter());
        }
    }//GEN-LAST:event_btnSearchActionPerformed

    public void searchAndDisplayResult(Query q) {
        String result = irApp.timKiem2(sds, search, q);
        txtResult.setText(result);
    }
    
    private void btnAdvanceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdvanceActionPerformed
        AdvanceSearchDialog a = new AdvanceSearchDialog(this);
        a.setVisible(true);
    }//GEN-LAST:event_btnAdvanceActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[])  throws MalformedURLException {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        //Khởi tạo GATE
        //    
        try {
            Gate.init();
            File gateHome = Gate.getGateHome();
            File pluginsHome = new File(gateHome, "plugins");
            Gate.getCreoleRegister().registerDirectories(new File(pluginsHome, "ANNIE").toURL());
            Out.prln("GATE initialised...");
        }
        catch (GateException gex) {
            Err.prln("cannot initialise GATE...");
            gex.printStackTrace();
            return;
        }
        
        irApp = new InformationRetrievalApp();
        
        try {
            SerialAnalyserController annieController =
                    (SerialAnalyserController)Factory.createResource("gate.creole.SerialAnalyserController",
                                                                    Factory.newFeatureMap(), 
                                                                    Factory.newFeatureMap(),
                                                                    "ANNIE_" + Gate.genSym());
            
            //DefaultTokeniser token = (DefaultTokeniser)Factory.createResource("gate.creole.tokeniser.DefaultTokeniser", Factory.newFeatureMap());
            for(int i = 0; i < ANNIEConstants.PR_NAMES.length; i++) {
                FeatureMap params = Factory.newFeatureMap(); // use default parameters
                ProcessingResource pr = (ProcessingResource)Factory.createResource(ANNIEConstants.PR_NAMES[i], params);
                // add the PR to the pipeline controller
                annieController.add(pr);
            }

            ////1. open a serial data store
            File folder = new File(irApp.getSDF());
            if(folder.list().length > 0) {
                sds = Factory.openDataStore("gate.persist.SerialDataStore", irApp.getSDP());
                sds.delete();
                folder.mkdir();
            }
            
            sds = Factory.createDataStore("gate.persist.SerialDataStore", irApp.getSDP());
            sds.open();
            
            
            //2. create transient corpus with docs
            Corpus corpus =  irApp.createTestCorpus();
            annieController.setCorpus(corpus);
            annieController.execute();
            //3. serialize corpus in Serial datastore
            Corpus serialCorpus = (Corpus)sds.adopt(corpus,null);
            

            //4. sync datastore
            sds.sync(serialCorpus);

            //5. index the serialized corpus
            IndexedCorpus indexedCorpus = (IndexedCorpus)serialCorpus;

            //Khởi tạo Index 
            DefaultIndexDefinition did = new DefaultIndexDefinition();
            // Sử dụng kỹ thuật Lucene IR
            //  
            did.setIrEngineClassName(gate.creole.ir.lucene.LuceneIREngine.class.getName());

            //Xác định vị trí index
            did.setIndexLocation(irApp.getIL());

            //Xác định trường index
            did.addIndexField(new IndexField("content", new DocumentContentReader(), false));
            did.addIndexField(new IndexField("title", null, false));

            indexedCorpus.setIndexDefinition(did);

            //5.5 ask the IndexManager to create the index (delete it beforehand if already existing)
            indexedCorpus.getIndexManager().deleteIndex();
            indexedCorpus.getIndexManager().createIndex();
            indexedCorpus.getIndexManager().optimizeIndex();

            //7. search in index

            //7.2.  create the proper Search subclass
            //    since we're using the Lucene IR engine, use LuceneSearch
            search = new LuceneSearch();
            //    the Search instance needs to know which corpus to search
            search.setCorpus(indexedCorpus);
        }
        catch(Exception ex) {
            ex.printStackTrace(Err.getPrintWriter());
        }
        
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdvance;
    private javax.swing.JButton btnSearch;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField txtQuery;
    private javax.swing.JTextPane txtResult;
    // End of variables declaration//GEN-END:variables
}
